<?php

/**
 *  分红计算
 */

namespace app\award;

use app\models\MonthProfit;
use app\models\order\Order;
use app\models\user\User;
use app\models\user\UserLevel;
use app\models\ZSetting;
use app\services\Chain;
use yii\helpers\ArrayHelper;

/**
 * Class Profit
 * @package app\award
 *
 * 1) 计算自己整个团队的订单数(金额)
 * 2) 计算子团队
 * 3) 自己 减去 全部团队
 *
 */
class Profit
{
    static $test = false;


    public static function getList($test = false)
    {
        self::$test = $test;

        // 1) 找出 创2, 创3
        $users = User::find()
            ->where(['level' => [
                UserLevel::$keys['vip3'],
                UserLevel::$keys['vip4']
            ]])
            ->select(['id'])
            ->column();

        $data = [];
        foreach ($users as $user) {

            $children = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip1'],
                UserLevel::$keys['vip2'],
                UserLevel::$keys['vip3'],
                UserLevel::$keys['vip4'],
            ], ['id']);
            $children = ArrayHelper::getColumn($children, 'id');

            $manager = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip3'],
                UserLevel::$keys['vip4'],
            ], ['id']);
            $manager = ArrayHelper::getColumn($manager, 'id');

            $data[] = [
                'id' => $user,
                'children' => $children,
                'manager' => $manager,
            ];
        }

        // 去重(本身不能是子团队)
        $x = ArrayHelper::getColumn($data, 'manager');
        foreach ($x as $k => $v) {
            if (!$v) {
                unset($x[$k]);
            }
        }

        // 去子团队
        foreach ($users as $key => $user) {
            foreach ($x as $item) {
                if (in_array($user, $item)) {
                    unset($users[$key]);
                }
            }
        }

        // var_dump($data, $users);exit;

        $users = self::getOrder($users);
        // $users = array_reverse($users);

        // var_dump($users);exit;

        $data = [];
        foreach ($users as $item) {
            // $amount = $item['amount'] - self::sub_max($users, $item['manager']);
            // $amount = $item['amount'] - self::sub($users, $item['manager']);

            // 剩余数量
            // $sub_quantity = self::sub_quantity($users, $item['manager']);

            // 减掉第1链
            $sub_quantity = self::quantity($item, $users);
            // 减掉之前返了的的
            $done = (int)MonthProfit::find()
                ->where(['user_id' => $item['id']])
                ->sum('real_quantity');
            // if ($item['id'] == 11195) {
            //     var_dump($done);
            // }
            $q = $item['quantity'] - $sub_quantity;
            $q = $q - $done;
            if ($q < 0) {
                $q = 0;
            }

            $data[] = [
                'id' => $item['id'],
                'amount' => $item['amount'],        // 比例
                'quantity' => $item['quantity'],    // 完成了多少金额订单
                'real_quantity' => $q,              // 减掉子团队(以及之前返过的)剩下的订单金额
                'result_amount' => $q * $item['amount'], // 金额 * 比例
                // 'manager' => $item['manager'],
                // 'children' => $item['children'],
            ];
        }

        // var_dump($data);exit;

        return $data;
    }

    // 减全部或者最大不对, 要减第1梯队
    public static function quantity($item, $users)
    {
        $sum = 0;

        foreach ($item['manager'] as $v) {
            $one = Chain::getReferrerChainOneId($v, [
                UserLevel::$keys['vip3'],
                UserLevel::$keys['vip4']
            ]);
            if ($one && $one['id'] == $item['id'] && isset($users[$v]['quantity'])) {
                $sum += $users[$v]['quantity'];
                // if ($item['id'] == 11196) {
                //     echo $v, ' ', $item['id'], ' ', $one['id'], ' ', "\n";
                //     var_dump($users[$v]);
                // }
            }
        }

        return $sum;
    }

    protected static function getOrder($users, $list = [])
    {
        foreach ($users as $user) {

            $children = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip1'],
                UserLevel::$keys['vip2'],
                UserLevel::$keys['vip3'],
                UserLevel::$keys['vip4'],
            ], ['id']);
            $children = ArrayHelper::getColumn($children, 'id');

            $manager = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip3'],
                UserLevel::$keys['vip4'],
            ], ['id']);
            $manager = ArrayHelper::getColumn($manager, 'id');

            $u = [
                'id' => $user,
                'children' => $children,
                'manager' => $manager
            ];

            $query = Order::find()
                ->where(['user_id' => array_merge([$user], $children)])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                // 只记算 报单 与 复购区
                ->andWhere(['area' => 1]);
                // 本月
                // ->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
                // 上个月的 (线上要用上个月的)
                // ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
                // ->all();

            // 测试
            if (!self::$test) {
                // 应该是累计, 不只是算上个月的
                // $query->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')");
            }

            // if ($user == 11199) {
            //     var_dump(array_merge([$user], $children), $children, $query->createCommand()->getRawSql());exit;
            // }

            $orders = $query->all();

            $sum = 0;
            foreach ($orders as $order) {
                // $sum += $order['total_quantity'];
                // 这里改成了金额
                $sum += $order['total_pay'];
            }

            $u['quantity'] = $sum;
            $u['amount'] = self::getAmount($u);

            // if ($u['id'] == 11194) {
            //     var_dump($u);exit;
            // }

            if (!key_exists($user, $list)) {
                $list[$user] = $u;
            }

            if ($manager) {
                $list = self::getOrder($manager, $list);
            }

        }

        return $list;
    }

    // 获取单价
    protected static function getAmount($user)
    {
        $quantity = $user['quantity'];

        $model = ZSetting::find()
            ->where(['<=', 'start', $quantity])
            ->andWhere(['>=', 'end', $quantity])
            ->one();

        if ($model) {
            // return $model->amount;
            // 这里改成了比例
            return $model->amount / 100;
        }

        return 0;
    }

    // 减去最大的
    public static function sub_max($users, $children)
    {
        // 找出需要的团队
        $list = [];
        foreach ($users as $key => $user) {
            if (in_array($key, $children)) {
                array_push($list, $user);
            }
        }

        $max = 0;
        if (!empty($list)) {
            foreach ($list as $item) {
                if ($item['amount'] > $max) {
                    $max = $item['amount'];
                }
            }
        }
        return $max;
    }

    // 需要减掉团队下面全部佣金
    public static function sub($users, $children)
    {
        // 找出需要的团队
        $list = [];
        foreach ($users as $key => $user) {
            if (in_array($key, $children)) {
                array_push($list, $user);
            }
        }

        $sum = 0;
        foreach ($list as $item) {
            $sum += $item['amount'];
        }
        return $sum;
    }

    // 用这个, 减去数量, 再乘以单价
    public static function sub_quantity($users, $manager)
    {
        // 找出需要的团队
        $list = [];
        foreach ($users as $key => $user) {
            if (in_array($key, $manager)) {
                // echo $key, "\n";
                array_push($list, $user);
            }
        }

        // var_dump($list);exit;

        $sum = 0;
        if (!empty($list)) {
            foreach ($list as $item) {
                $sum += $item['quantity'];
            }
        }
        return $sum;

        $max = 0;
        if (!empty($list)) {
            foreach ($list as $item) {
                if ($item['quantity'] > $max) {
                    $max = $item['quantity'];
                }
            }
        }
        return $max;
    }
}